//系统函数
game={
    paused:false,
    paused2:false,
    auto:false,
    over:false,
    players:new Array(),
    dead:new Array(),
    history:new Array(),
    selected_cards:new Array(),
    selected_targets:new Array(),
    selected_buttons:new Array(),
    cards:new Object(),
    characters:new Object(),
    skills:new Object(),
    global_skills:new Object()
}
filter={
    card:{

    },
    target:{

    }
}
ui={
    createPlayer:function(){
        var node=document.createElement("div");
        node.className="player";
        node.node=new Object();
        
        var node_avatar=document.createElement("div");
        node_avatar.className="avatar";
        node_avatar.dataset.style='empty';

        var node_e=document.createElement("div");
        node_e.className="equips";
        
        var node_e1=document.createElement("div");
        node_e1.className="equip1";
        node_e1.dataset.style='empty';
        
        var node_e2=document.createElement("div");
        node_e2.className="equip2";
        node_e2.dataset.style='empty';
        
        var node_e3=document.createElement("div");
        node_e3.className="equip3";
        node_e3.dataset.style='empty';
        
        var node_e4=document.createElement("div");
        node_e4.className="equip4";
        node_e4.dataset.style='empty';
        
        var node_j=document.createElement("div");
        node_j.className="judges";
        
        var node_m=document.createElement("div");
        node_m.className="marks";
        
        var node_c=document.createElement("div");
        node_c.className="special";
        
        var node_h1=document.createElement("div");
        node_h1.className="handcards1";
        
        var node_h2=document.createElement("div");
        node_h2.className="handcards2";
        
        var node_identity=document.createElement("div");
        node_identity.className="identity";
        
        var node_name=document.createElement("div");
        node_name.className="name"
        
        var node_hp=document.createElement("div");
        node_hp.className="hp";
        
        var node_hp1=document.createElement("div");
        node_hp1.className="hp1";
        
        var node_hp2=document.createElement("div");
        node_hp2.className="hp2";
        
        var node_count=document.createElement("div");
        node_count.className="count"
        
        node.appendChild(node_avatar);
        node.appendChild(node_e);
        node.appendChild(node_j);
        node.appendChild(node_m);
        node.appendChild(node_c);
        node.appendChild(node_h1);
        node.appendChild(node_h2);
        node.appendChild(node_identity);
        node.appendChild(node_hp);
        node.appendChild(node_name);
        node.appendChild(node_count);
        
        node_e.appendChild(node_e1);
        node_e.appendChild(node_e2);
        node_e.appendChild(node_e3);
        node_e.appendChild(node_e4);
        
        node_hp.appendChild(node_hp1);
        node_hp.appendChild(node_hp2);
        
        node.dataset.select=0;
        node.dataset.alive=1;
        node.dataset.flipped=0;
        node.dataset.linked=0;
        node.addEventListener("click",function(){clickTarget(this)});
        node.handcards=new Array();
        node.equips=new Array();
        node.judges=new Array();
        node.cards=new Array();
        node.mods=new Array();
        node.special=new Object();
        node.phase_skills=new Array();
        node.temp_skills=new Array();

        node.node.hp1=node_hp1;
        node.node.hp2=node_hp2;
        node.node.handcards1=node_h1;
        node.node.handcards2=node_h2;
        node.node.equip1=node_e1;
        node.node.equip2=node_e2;
        node.node.equip3=node_e3;
        node.node.equip4=node_e4;
        node.node.judges=node_j;
        node.node.special=node_c;
        node.node.count=node_count;
        node.node.avatar=node_avatar;
        node.node.identity=node_identity;
        node.node.name=node_name;
        
        return node;
    },
    createSpecial:function(id){
        var node=document.createElement('div');
        node.id=(evt.player.name+'_'+id);
        node.className='special';
        return node;
    },
    deleteDialog:function(){
        setTimeout('ui.dialog.container.removeChild(ui.dialog.deleting.shift());',config.duration);
    },
    createButton:function(type,button){
        var node=document.createElement('div');
        if(type=='character'){
            node.className='button';
            node.dataset.style='avatar';
            node.style.backgroundImage='url("character/image/'+button+'.jpg")';
            node.innerHTML='<p>'+translate(button)+'</p>';
        }
        else if(type=='card'){
            node.className='button';
            node.dataset.style='card';
            node.style.backgroundImage='url("card/image/'+button.name+'.png")';
            
            var info=document.createElement("div");
            info.className="cardInfo";
            if(translate(button.suit)!=undefined) info.innerHTML+=translate(button.suit);
            if(button.number!=undefined) info.innerHTML+=" "+button.number;
            node.appendChild(info);
            
            var name=get.name(button)
            var caption=document.createElement("div");
            caption.className="cardCaption";
            caption.innerHTML="";
            for(var i in name){
                caption.innerHTML+=name[i]+"<br/>";
            }
            node.appendChild(caption);
        }
        else if(type=='unknown'){
            node.className='button';
            node.dataset.style='card';
        }
        node.link=button;
        node.dataset.select=0;
        node.addEventListener('click',function(){clickButton(this)});
        return node;
    },
    createDialog:function(content){
        var node=document.createElement('div');
        node.className='dialog';
        node.buttons=new Array();
        node.disabled_buttons=new Array();
        
        var node2=document.createElement('div');
        node2.className='content';
        node.appendChild(node2);
        node.content=node2;
        
        content=ensureArray(content);
        for(var i in content){
            if(content[i].type==undefined) content[i].type='card';
        }
        
        for(var i in content){
            var h3=document.createElement('h3');
            h3.innerHTML=content[i].caption;
            node.content.appendChild(h3);
            for(var j in content[i].list){
                var button=ui.createButton(content[i].type,content[i].list[j]);
                node.buttons.push(button);
                node.content.appendChild(button);
            }
        }
        return node;
    },
    createCard:function(card){
        var node=document.createElement("div");

        node.suit=card[0];
        if(node.suit=='club'||node.suit=='spade')
            node.color='black';
        else
            node.color='red';
        node.number=card[1];
        node.name=card[2];
        node.className="card";
        
        var info=document.createElement("div");
        info.className="cardInfo";
        info.innerHTML=translate(node.suit)+" "+node.number;
        node.appendChild(info);
        
        var caption=document.createElement("div");
        caption.className="cardCaption";
        caption.innerHTML="";
        var name=translate(card[2]);
        for(var i in name){
            caption.innerHTML+=name[i]+"<br/>";
        }
        node.appendChild(caption);
        node.style.backgroundImage="url('cards/images/"+node.name+".png')";
        node.addEventListener('click',function(){clickCard(this)});
        node.dataset.select=0;
        
        return node
    },
    updateStyle:function(){
        if(ui.dialog.current==undefined||ui.dialog.current.content.offsetHeight<ui.dialog.current.offsetHeight){
            ui.dialog.container.className='dialogContainer';
        }
        else{
            ui.dialog.container.className='dialogContainer2';
        }
    },
    updatePlayer:function(){
        for(var i in game.players){
            var player=game.players[i];
            player.node.count.innerHTML=player.handcards.length;
            var hp=Math.max(0,player.hp);
            var losthp=Math.max(0,player.max_hp-hp);
            while(player.node.hp1.childNodes.length>hp){
                player.node.hp1.removeChild(player.node.hp1.firstChild);
            }
            while(player.node.hp1.childNodes.length<hp){
                player.node.hp1.appendChild(document.createElement('div'));
            }
            while(player.node.hp2.childNodes.length>losthp){
                player.node.hp2.removeChild(player.node.hp2.firstChild);
            }
            while(player.node.hp2.childNodes.length<losthp){
                player.node.hp2.appendChild(document.createElement('div'));
            }
        }
    },
    setPlayer:function(player,name,name2){
        var info=game.characters[name];
        player.name=name;
        player.node.avatar.style.backgroundImage='url("characters/images/'+name+'.jpg")';
        var name1=translate(name);
        for(var i in name1){
            player.node.name.innerHTML+=name1[i]+'<br/>';
        }
        player.sex=info[0];
        player.group=info[1];
        player.node.identity.style.background=translate(info[1]+'Color');
        for(var i=0;i<info[2];i++){
            player.node.hp1.appendChild(document.createElement('div'));
        }
        player.hp=info[2];
        player.max_hp=info[2];
        player.skills=info[3];

        if(name2!=undefined){
            player.skills=player.skills.concat(game.characters[name2][3]);
            player.max_hp=player.max_hp+game.characters[name2][2]-3;
            player.hp=player.max_hp;
            var node=document.createElement('div');
            node.className='avatar2';
            player.node.avatar2=node;
            player.node.count.dataset.style=2;
            player.appendChild(node);
            node.style.backgroundImage='url("characters/images/'+name2+'.jpg")';
        }
    },
    dialog:{
        list:new Array(),
        deleting:new Array()
    },
    translate:{
        zhu:"主",
        zhong:"忠",
        nei:"内",
        fan:"反",
        heart:"♥︎",
        diamond:"♦︎",
        spade:"♠︎",
        club:"♣︎",
        heart2:"红桃",
        diamond2:"方片",
        spade2:"黑桃",
        club2:"梅花",
        ok:"确定",
        cancel:"放弃",
        yes:"确定",
        no:"取消",
        end:"结束",
        weiColor:"#b0d0e2",
        shuColor:"#ffddb9",
        wuColor:"#b2d9a9",
        qunColor:"#f6f6f6",
        fire:"火",
        thunder:"雷",
        replay:"重新开始"
    }
}
api={

}
function Event(){
    this.new=new Array();
    this.skip=new Array();
    this.step=0;
    this.finished=false;
    this.reason=evt.name;
}
function PrepareTable(){
    evt=new Object();
    evt=new Event('PrepareTable');
    evt.content=function(step){
        switch(step){
            case 0:
            
            var arena=document.createElement("div");
            arena.id="arena";
            document.body.appendChild(arena);
            
            var cardPile=document.createElement("div");
            cardPile.id="cardPile";
            arena.appendChild(cardPile);
            ui.cardPile=cardPile;
            
            var discardPile=document.createElement("div");
            discardPile.id="discardPile";
            arena.appendChild(discardPile);
            ui.discardPile=discardPile;
            
            var sidebar1=document.createElement("div");
            sidebar1.className="sidebar";
            sidebar1.id="sidebar1";
            arena.appendChild(sidebar1);
            ui.sidebar1=sidebar1;
            
            var sidebar2=document.createElement("div");
            sidebar2.className="sidebar";
            sidebar2.id="sidebar2";
            arena.appendChild(sidebar2);
            ui.sidebar2=sidebar2;
            
            var temp=document.createElement("div");
            temp.id="temp";
            arena.appendChild(temp);
            ui.temp=temp;

            var num=config[config.mode].player_number;
            if(num==undefined) num=config.default.player_number;
            for(var i=0;i<num;i++){
                game.players[i]=ui.createPlayer();
                game.players[i].seat=i;
            }
            game.me=game.players[0];
            for(var i=0;i<num;i++){
                if(i==0){
                    game.players[0].previous=game.players[num-1];
                }
                else{
                    game.players[i].previous=game.players[i-1];
                }
                if(i==num-1){
                    game.players[num-1].next=game.players[0];
                }
                else{
                    game.players[i].next=game.players[i+1];
                }
            }
            var table=document.createElement("table");
            table.setAttribute("cellspacing",0);
            arena.appendChild(table);
            
            var tr1=document.createElement("tr");
            var td1=document.createElement("td");
            var td2=document.createElement("td");
            var td3=document.createElement("td");
            
            td2.id="top";
            td1.style.textAlign="center";
            td2.style.textAlign="center";
            td3.style.textAlign="center";

            if(num%2==1){
                td1.style.textAlign="right";
                td3.style.textAlign="left";
            }
            
            tr1.appendChild(td1);
            tr1.appendChild(td2);
            tr1.appendChild(td3);
            table.appendChild(tr1);
            
            var tr2=document.createElement("tr");
            var td4=document.createElement("td");
            var td5=document.createElement("td");
            var td6=document.createElement("td");
            
            var confirm=document.createElement("div");
            confirm.className='confirm';
            confirm.style.opacity=0;
            ui.dialog.confirm=confirm;
            
            var skills=document.createElement("div");
            skills.className='confirm';
            skills.style.opacity=0;
            ui.dialog.skills=skills;
            
            var control=document.createElement("div");
            control.className='confirm';
            control.style.opacity=0;
            ui.dialog.control=control;
            
            var container=document.createElement("div");
            container.className='dialogContainer';
            ui.dialog.container=container;
            container.appendChild(confirm);
            container.appendChild(skills);
            container.appendChild(control);
            
            td5.rowSpan=2;
            td5.appendChild(container);
            td4.style.textAlign="left";
            td5.style.textAlign="center";
            td6.style.textAlign="right";
            
            tr2.appendChild(td4);
            tr2.appendChild(td5);
            tr2.appendChild(td6);
            table.appendChild(tr2);
            
            var tr3=document.createElement("tr");
            var td7=document.createElement("td");
            var td8=document.createElement("td");
            
            td7.style.textAlign="left";
            td8.style.textAlign="right";
            
            tr3.appendChild(td7);
            tr3.appendChild(td8);
            table.appendChild(tr3);

            switch(num){
                case 2:
                td2.appendChild(game.players[1]);
                break;
                case 3:
                td1.appendChild(game.players[2]);
                td3.appendChild(game.players[1]);
                break;
                case 4:
                td4.appendChild(game.players[3]);
                td2.appendChild(game.players[2]);
                td6.appendChild(game.players[1]);
                break;
                case 5:
                td1.appendChild(game.players[3]);
                td3.appendChild(game.players[2]);
                td4.appendChild(game.players[4]);
                td6.appendChild(game.players[1]);
                break;
                case 6:
                td1.appendChild(game.players[4]);
                td2.appendChild(game.players[3]);
                td3.appendChild(game.players[2]);
                td4.appendChild(game.players[5]);
                td6.appendChild(game.players[1]);
                break;
                case 7:
                td1.appendChild(game.players[4]);
                td3.appendChild(game.players[3]);
                td4.appendChild(game.players[5]);
                td6.appendChild(game.players[2]);
                td7.appendChild(game.players[6]);
                td8.appendChild(game.players[1]);
                break;
                case 8:
                td1.appendChild(game.players[5]);
                td2.appendChild(game.players[4]);
                td3.appendChild(game.players[3]);
                td4.appendChild(game.players[6]);
                td6.appendChild(game.players[2]);
                td7.appendChild(game.players[7]);
                td8.appendChild(game.players[1]);
            }
            
            var tr4=document.createElement("tr");
            var th=document.createElement("th");
            th.colSpan=3;
            tr4.appendChild(th);
            table.appendChild(tr4);
            
            var node=document.createElement("div");
            node.id="me";
            ui.me=node;
            th.appendChild(node);
            var table2=document.createElement("table");
            table2.setAttribute("cellspacing",0);
            node.appendChild(table2);
            node.style.bottom=0;
            
            var tr5=document.createElement("tr");
            var td9=document.createElement("td");
            var td10=document.createElement("td");
            var td11=document.createElement("td");
            
            td10.appendChild(game.players[0]);
            td10.id='me_td';
            
            var node2=document.createElement('div');
            node2.id='h1';
            node2.className='handcards1';
            td9.appendChild(node2);
            game.me.node.handcards1=node2;
            
            var node3=document.createElement('div');
            node3.id='h2';
            node3.className='handcards2';
            td11.appendChild(node3);
            game.me.node.handcards2=node3;
            
            tr5.appendChild(td9);
            tr5.appendChild(td10);
            tr5.appendChild(td11);
            table2.appendChild(tr5);

            break;
            case 1:
            ui.me.style.opacity=0;
            for(var i=1;i<game.players.length;i++){
                game.players[i].style.opacity=0;
            }
            var num=parseInt(game.players.length/2-0.5);
            for(var i=1;i<num+1;i++)
                game.players[i].style.right='100px';
            for(var i=game.players.length-1;i>=game.players.length-num;i--)
                game.players[i].style.left='100px';
            delay();
            break;
            case 2:
            ui.me.style.opacity=1;
            for(var i=1;i<game.players.length;i++){
                game.players[i].style.opacity=1;
                if(game.players[i].style.left) game.players[i].style.left=0;
                if(game.players[i].style.right) game.players[i].style.right=0;
            }
            delay(2);
            break;
            case 3:
            ui.me.removeAttribute("style");
            for(var i=1;i<game.players.length;i++){
                game.players[i].removeAttribute("style");
            }
            break;
            case 4:
            var cardList=new Array();
            for(var i in config.cards){
                var pack=eval(config.cards[i]+"Card");
                for(var j in pack.cards){
                    game.cards[j]=pack.cards[j];
                }
                for(var j in pack.skills){
                    game.skills[j]=pack.skills[j];
                }
                for(var j in pack.api){
                    api[j]=pack.api[j];
                }
                for(var j in pack.translate){
                    ui.translate[j]=pack.translate[j];
                }
                for(var j in pack.list){
                    cardList.push(pack.list[j]);
                }
            }
            cardList.sort(randomSort);
            for(var i in cardList){
                document.getElementById('cardPile').appendChild(ui.createCard(cardList[i]));
            }
            break;
            default:
            finish();
            Game();
        }
    }
    gameLoop();
}
function addEvent(name){
    var next=new Event();
    next.name=name;
    evt.new.push(next);
    return next;
}
function gameLoop(){
    if(game.paused) return;
    if(game.paused2) return;
    if(game.over){
        gameOver();
        return;
    }
    if(evt.step>99){
        alert(evt.name+': 步数超上限，忘加finish()了？');
        return;
    }
    //由上一步产生的新事件
    if(evt.new.length>0){
        var next=evt.new.shift();
        var skip=false;
        if(next.player){
            var flags=getFlags(next.player,'skip');
            for(var i in flags){
                if(flags[i].skip(next)){
                    if(flags[i].expire.triggered!=undefined){
                        if(flags[i].expire.triggered<=1)
                            removeItem(next.player.flags,flags[i]);
                        else
                            flags[i].expire.triggered--;
                    }
                    skip=true;
                }
            }
        }
        if(skip==false){
            next.parent=evt;
            evt=next;
            game.history.push(evt);
        }
    }
    //事件完成返回上一级
    else if(evt.finished){
        for(var i in game.players){
            var flags=getFlags(game.players[i],'expire');
            for(var i in flags){
                if(flags[i].expire.event==evt)
                    removeItem(game.players[i].flags,flags[i]);
            }
            if(evt.name=='Phase'){
                for(var j in flags){
                    if(flags[j].expire.phase!=undefined){
                        if(flags[j].expire.phase<=1)
                             removeItem(game.players[i].flags,flags[j]);
                        else
                            flags[j].expire.phase--;
                    }
                    if(flags[j].expire.own_phase!=undefined&&evt.player==game.players[i]){
                        if(flags[j].expire.own_phase<=1)
                            removeItem(evt.player.flags,flags[j]);
                        else
                            flags[j].expire.own_phase--;
                    }
                }
            }
        }
        if(evt.return!=undefined) evt.parent.result=evt.return;
        evt=evt.parent;
    }
    else{
        evt.content(evt.step);
        evt.step++;
        if(evt.content.length==0&&evt.step){
            finish();
        }
    }
    gameLoop();
}
function getFlags(player,item){
    var flags=new Array();
    for(var i in player.skills){
        var skill=game.skills[player.skills][i];
        if(skill.flag&&skill.flag[item]!=undefined)
            flags.push(skill.flag);
    }
    for(var i in player.flags){
        if(player.flags[i][item]!=undefined)
            flags.push(player.flags[i]);
        if(player.flags[i].skill){
            var skill=game.skills[player.flags[i].skill(player)];
            if(skill.flag&&skill.flag[item]!=undefined)
                flags.push(skill.flag);
        }
    }
    return flags;
}
function removeItem(arr,item){
    for(var i in arr){
        if(arr[i]==item){
            arr.splice(i,1);
            return true;
        }
    }
    return false;
}
function finish(event){
    event=event||evt;
    event.finished=true;
}
function goto(step){
    evt.step=step-1;
}
function redo(){
    evt.step--;
}
function pause(){
    game.paused=true;
}
function pause2(){
    game.paused2=true;
}
function resume(){
    game.paused=false;
    gameLoop();
}
function resume2(){
    game.paused2=false;
    gameLoop();
}
function delay(time,time2){
    if(time==undefined) time=1;
    if(time2==undefined) time2=0;
    pause();
    setTimeout("resume()",time*config.duration+time2);
}
function randomSort(a, b){
    return Math.random() - 0.5;
}
function translate(str){
    for(var i in ui.translate){
        if(i==str){
            return ui.translate[i];
        }
    }
    return str;
}
//游戏函数
function openDialog(){
    closeDialog('prompt');
    var node=document.createElement('div');
    node.className='dialog';
    node.buttons=new Array();
    node.disabled_buttons=new Array();
        
    var node2=document.createElement('div');
    node2.className='content';
    node.appendChild(node2);
    node.content=node2;
    
    for(var i=0;i<arguments.length;i++){
        if(typeof(arguments[i])=='string'){
            var h3=document.createElement('h3');
            h3.innerHTML=arguments[i];
            node.content.appendChild(h3);
        }
        else if(isArray(arguments[i])){
            var list,type;
            if(isCard(arguments[i][0])){
                list=arguments[i];
                type='card';
            }
            else{
                list=arguments[i][0];
                type=arguments[i][1];
            }
            for(var j in list){
                var button=ui.createButton(type,list[j]);
                node.buttons.push(button);
                node.content.appendChild(button);
            }
        }
    }

    node.style.opacity=0;
    if(ui.dialog.current) ui.dialog.current.style.opacity=0;
    ui.dialog.list.push(node);
    ui.dialog.current=node;
    ui.dialog.container.appendChild(ui.dialog.current);
    ui.updateStyle();
    node.style.opacity=1;
}
function closeDialog(id){
    var dialog;
    if(id!=undefined){
        for(var i in ui.dialog.list){
            if(ui.dialog.list[i].id==id){
                dialog=ui.dialog.list[i];
                break;
            }
        }
        if(dialog==undefined) return;
    }
    else dialog=ui.dialog.current;
    removeItem(ui.dialog.list,dialog);
    ui.dialog.deleting.push(dialog);
    dialog.style.opacity=0;
    ui.deleteDialog();

    if(dialog==ui.dialog.current){
        if(ui.dialog.list.length>0){
            ui.dialog.current=ui.dialog.list[ui.dialog.list.length-1];
            ui.dialog.current.style.opacity=1;
        }
        else{
            delete ui.dialog.current;
        }
    }

    ui.updateStyle();
}


function isArray(obj){
    return Object.prototype.toString.call(obj) === '[object Array]'; 
}
function isDiv(obj) {
  return Object.prototype.toString.call(obj) === '[object HTMLDivElement]'; 
}
function isPlayer(obj){
    if(isDiv(obj)==false) return false;
    return(obj.className=='player');
}
function isCard(obj){
    if(isDiv(obj)==false) return false;
    return (obj.className=='card');
}
function isButton(obj){
    return(obj.className=='button');
}